#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;

int n = 5;
int a[5];
int t[5];

int calc(int x)
{
	int ans = 0;
	while(x)
	{
		ans ++;
		x &= x - 1;
	}
	return ans;
}

int main()
{
	int T; cin >> T;
	while(T --)
	{
		memset(a, 0, sizeof a);
		for(int i = 0;i < n;i ++)
		{
			for(int j = n - 1;j >= 0;j --)
			{
				char ch; cin >> ch;
				if(ch == '0') a[i] |= (1 << j);
			}
		}

		int ans = INF;
		// 枚举第一行的所有按法
		for(int st = 0;st < (1 << n);st ++)
		{
			memcpy(t, a, sizeof a);
			int push = st, cnt = 0;
			for(int i = 0;i < n;i ++)
			{
				cnt += calc(push);
				t[i] ^= push ^ (push << 1) ^ (push >> 1);
				t[i] &= (1 << n) - 1;
				t[i + 1] ^= push;
				push = t[i];
			}
			if(t[n - 1] == 0) ans = min(ans, cnt);
		}
		if(ans > 6) cout << -1 << endl;
		else cout << ans << endl;
	}
	return 0;
}